package com.atguigu.gmall.list.listener;

import com.atguigu.gmall.list.service.ListService;
import com.atguigu.gmall.rabbitmq.config.RabbitConst;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;


/**
 * @Author: lx
 * @Time: 11:36
 * @Description:
 *  消息的监听器
 */
@Component
public class ESConsumer {

    @Autowired
    private ListService listService;

    //接收上架消息
    @RabbitListener(bindings = {@QueueBinding(
            value = @Queue(value = RabbitConst.QUEUE_GOODS_UPPER,
                    durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = RabbitConst.EXCHANGE_DIRECT_GOODS),
            key = {RabbitConst.ROUTING_GOODS_UPPER}
    )})
    public void receiverUpperMessage(Long skuId, Channel channel, Message message){
        try {
            System.out.println("接收到的SkuId：" + skuId);
            //添加索引库中索引
            listService.onSale(skuId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //接收下架消息
    @RabbitListener(bindings = {@QueueBinding(
            value = @Queue(value = RabbitConst.QUEUE_GOODS_LOWER,
                    durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = RabbitConst.EXCHANGE_DIRECT_GOODS),
            key = {RabbitConst.ROUTING_GOODS_LOWER}
    )})
    public void receiverLowerMessage(Long skuId, Channel channel, Message message){
        try {
            System.out.println("接收到的SkuId：" + skuId);
            //删除索引
            listService.cancelSale(skuId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
